
import re
import os
import sys
import random
import shutil

class Manager:

    mainPath = ''
    allPathArr = []
    prefix = ''
    #例如 XYX,XYP,XYLive....
    allOldPrefixClassNameArr = []
    allOldPrefixVarNameArr = []
    allNeedReplaceNameArr = []
    oldClassNamePrefixPath = ''
    oldVariableNamePrefixPath = ''
    project_pbxproPath = ''
    endNeedReplaceNameArr = []
    myPrefixReplaceNameArr = []

    def start(self):
        self.oldClassNamePrefixPath = os.path.dirname(__file__) + '/oldClassNamePrefix.txt'
        self.oldVariableNamePrefixPath = os.path.dirname(__file__) + '/oldVariableNamePrefix.txt'
        self.project_pbxproPath =  os.path.dirname(__file__) + '/project_pbxpro.txt'
        if os.path.exists(self.oldClassNamePrefixPath) and os.path.exists(self.oldVariableNamePrefixPath):
            ClassNameFile = open(self.oldClassNamePrefixPath, 'r')
            self.allOldPrefixClassNameArr = ClassNameFile.readlines()
            self.allOldPrefixClassNameArr = [line.strip() for line in self.allOldPrefixClassNameArr]
            VariableName = open(self.oldVariableNamePrefixPath, 'r')
            self.allOldPrefixVarNameArr = VariableName.readlines()
            self.allOldPrefixVarNameArr = [line.strip() for line in self.allOldPrefixVarNameArr]
        else:
            print("目录下不存在oldClassNamePrefix.txt、oldVariableNamePrefix.txt文件")
            return
        
        print("拖入换皮路径")
        self.mainPath = input().strip()
        print('输入替换前缀')
        self.prefix = input().strip()
        if len(self.prefix) == 0:
            print("替换的前缀不能为空")
            return

        # 查找文件夹修改文件夹的名字
        print("修改文件夹名称 ----  名称修改开始")
        old_name = self.allOldPrefixClassNameArr[0]
        old_pattern = re.compile(r'\{old_name}')
        for folder_name in os.listdir(self.mainPath):
            if os.path.isdir(os.path.join(self.mainPath, folder_name)):
                match = old_pattern.search(folder_name)
                if match:
                    new_folder_name = old_pattern.sub(self.prefix, folder_name)
                    os.rename(os.path.join(self.mainPath, folder_name),
                    os.path.join(self.mainPath, new_folder_name))
                    print(f'Renamed: {folder_name} to {new_folder_name}')
        print("修改文件夹名称 ----  名称修改结束")


        for root, dirs, files in os.walk(self.mainPath):
            for file in files:
                path = os.path.join(root, file)
                bool = path.endswith((".storyboard",".xib",".h",".m",".swift",".pch",".txt"))
                if bool == True :
                    if any(words in file for words in self.allOldPrefixClassNameArr) == True:
                        file_name = file.split('.')[0]
                        self.allNeedReplaceNameArr.append(file_name)
                    self.allPathArr.append(path)

        for path in self.allPathArr:
            if path.endswith('.h') == True:
                self.getHClassName(path)
            elif path.endswith('.m') == True:
                self.getMClassName(path)
            elif path.endswith('.swift') == True:
                self.getSwiftClassName(path)

        unique_set = set(self.allNeedReplaceNameArr)
        self.endNeedReplaceNameArr = list(unique_set)
        print(self.endNeedReplaceNameArr)
        for oldName in self.endNeedReplaceNameArr:
            locals()
            newName = oldName
            for oldPrefix in self.allOldPrefixClassNameArr:
                locals()
                if oldPrefix in oldName:
                    pattern = oldPrefix
                    result = re.findall(pattern, oldName)
                    if len(result) > 0:
                        oldPrefix = result[0]
                        newName = oldName.replace(oldPrefix, self.prefix)
                    break
                    #  下面是会随机加上 2 个数
                    # pattern = oldPrefix + r'[A-Za-z0-9]{2}_'  # 匹配双引号之间的内容
                    # result = re.findall(pattern, oldName)
                    # if len(result) > 0:
                        # oldPrefix = result[0]
                        #  这里有在末尾有随机加上 2 位数数据
                        # newName = oldName.replace(oldPrefix, self.prefix+self.generate_code(2))
                    # break
            self.myPrefixReplaceNameArr.append(newName)

        for path in self.allPathArr:
            if path.endswith('.pch') == True:
                self.pchReplace(path)
            else:
                self.otherReplace(path)
        if os.path.exists(self.project_pbxproPath):
            self.ppFileReplace(self.project_pbxproPath)
            
    def generate_code(self,code_len=4):
        all_charts = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        last_pos = len(all_charts) - 1
        code = ''
        for _ in range(code_len):
            index = random.randint(0, last_pos)
            code += all_charts[index]
        return code


    def ppFileReplace(self,path):
        locals()
        print(path)
        os.chmod(path, 0o777)
        codefile = open(path, 'r');
        codeText = codefile.read()
        index = 0
        for oldPrefix in self.endNeedReplaceNameArr:
            codeText = codeText.replace(oldPrefix+'.h',self.myPrefixReplaceNameArr[index]+'.h')
            codeText = codeText.replace(oldPrefix+'.m',self.myPrefixReplaceNameArr[index]+'.m')
            codeText = codeText.replace(oldPrefix+'.xib',self.myPrefixReplaceNameArr[index]+'.xib')
            codeText = codeText.replace(oldPrefix+'.swift',self.myPrefixReplaceNameArr[index]+'.swift')
            codeText = codeText.replace(oldPrefix+'.storyboard',self.myPrefixReplaceNameArr[index]+'.storyboard')
            index = index + 1
        newFile = open(path, 'w')
        newFile.write(codeText)
        newFile.close()

    def pchReplace(self,path):
        locals()
        print(path)
        os.chmod(path, 0o777)
        codefile = open(path, 'r');
        codeText = codefile.read()
        index = 0
        for oldPrefix in self.endNeedReplaceNameArr:
            codeText = codeText.replace(oldPrefix,self.myPrefixReplaceNameArr[index])
            index = index + 1
        newFile = open(path, 'w')
        newFile.write(codeText)
        newFile.close()

    def otherReplace(self,path):
        locals()
        print(path)
        os.chmod(path, 0o777)
        codefile = open(path, 'r');
        codeText = codefile.read()
        index = 0
        for oldPrefix in self.endNeedReplaceNameArr:
            codeText = codeText.replace(oldPrefix,self.myPrefixReplaceNameArr[index])
            index = index + 1
        newFile = open(path, 'w')
        newFile.write(codeText)
        newFile.close()

        newPath = os.path.dirname(__file__) + '/allCode'+self.prefix+'/'
        isExists = os.path.exists(newPath)
        if not isExists:
            os.makedirs(newPath)
        newName = path
        fileName = os.path.basename(path)
        indexB = 0
        for oldPrefix in self.endNeedReplaceNameArr:
            locals()
            if oldPrefix in fileName:
                newfileName = fileName.replace(oldPrefix,self.myPrefixReplaceNameArr[indexB])
                newName = path.replace(fileName, newfileName)
                # shutil.copy(path, newPath+newfileName)
                break
            indexB = indexB + 1
        os.rename(path, newName)

    def getHClassName(self,path):
        print(path)
        os.chmod(path, 0o777)
        codefile = open(path, 'r');
        codeText = codefile.read()
        interfacepattern = r'@interface(.*?):'  # 匹配双引号之间的内容
        interfaceresult = re.findall(interfacepattern, codeText)
        # print(interfaceresult)
        for name in interfaceresult:
            if any(words in name for words in self.allOldPrefixClassNameArr) == True:
                file_name = name.split('.')[0]
                self.allNeedReplaceNameArr.append(file_name.strip())

        delegatepattern = r'@protocol(.*?)<'  # 匹配双引号之间的内容
        delegateresult = re.findall(delegatepattern, codeText)
        for name in delegateresult:
            if any(words in name for words in self.allOldPrefixClassNameArr) == True:
                file_name = name.split('.')[0]
                self.allNeedReplaceNameArr.append(file_name.strip())
        # print(delegateresult)


    def getMClassName(self,path):
        print(path)
        os.chmod(path, 0o777)
        codefile = open(path, 'r');
        codeText = codefile.read()
        interfacepattern = r'@interface(.*?):'  # 匹配双引号之间的内容
        interfaceresult = re.findall(interfacepattern, codeText)
        # print(interfaceresult)
        for name in interfaceresult:
            if any(words in name for words in self.allOldPrefixClassNameArr) == True:
                file_name = name.split('.')[0]
                self.allNeedReplaceNameArr.append(file_name.strip())

    def getSwiftClassName(self,path):
        print(path)
        os.chmod(path, 0o777)
        codefile = open(path, 'r');
        codeText = codefile.read()
        classpattern = r'class (.*?){'  # 匹配双引号之间的内容
        classresult = re.findall(classpattern, codeText)
        # print(classresult)
        for name in classresult:
            if any(words in name for words in self.allOldPrefixClassNameArr) == True:
                file_name = name.split(':')[0]
                self.allNeedReplaceNameArr.append(file_name.strip())
        protocolpattern = r'protocol (.*?){'  # 匹配双引号之间的内容
        protocolresult = re.findall(protocolpattern, codeText)
        # print(protocolresult)
        for name in protocolresult:
            if any(words in name for words in self.allOldPrefixClassNameArr) == True:
                file_name = name.split(':')[0]
                self.allNeedReplaceNameArr.append(file_name.strip())





huanpi = Manager()
huanpi.start()
